import {
  login,
  logout,
  getUserInfo
} from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import {
  Message
} from 'element-ui'

const user = {
  state: {
    token: getToken(),
    name: '',
    info:{}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, info) => {
      console.log(info)
      state.info = info
      state.name = info.name
    }
  },

  actions: {
    // 用户名登录
    login({
      commit
    }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password.trim()
      const code = userInfo.code.trim()
      return new Promise((resolve, reject) => {
        login(username, password,code).then(data => {
          if(data.result){
            commit('SET_TOKEN', data.token)
            setToken(data.token)
            resolve()
          }else{
            Message.error(data.errMsg)
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    getUserInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(data => {
          console.log(data)
          commit('SET_NAME', data.info)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
